using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XcoAppSpaces.Core;
using XcoAppSpaces.Core.Ports;
using System.Threading;
using NUnit.Framework;
using XcoAppSpaces.Serialization.Json;
using XcoAppSpaces.Contracts.Exceptions;
using XcoAppSpaces.Transport.Sockets;

namespace test.XcoAppSpaces.Core
{
	[TestFixture]
	public class testTcpTransportAuthentication
	{
		[Test]
		public void AuthenticationSuccessful_ConfigString()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000;tcp.key=test1234567890"),
				space2 = new XcoAppSpace("tcp.port=8001;tcp.key=test1234567890"))
			{
				var port = new Port<int>();
				space1.RunWorker(port);

				var remotePort = space2.ConnectWorker<Port<int>>(Environment.MachineName + ":8000");

				remotePort.Post(1);
				Assert.AreEqual(1, port.Receive(1000).Result);
			}
		}

		[Test]
		public void AuthenticationSuccessful_FluentConfig()
		{
			using (XcoAppSpace space1 = XcoAppSpace.Configure.UsingService<XcoTCPTransportService>().OnPort(8000).WithAuthenticationKey("1234"),
				space2 = XcoAppSpace.Configure.UsingService<XcoTCPTransportService>().OnPort(8001).WithAuthenticationKey("1234"))
			{
				var port = new Port<int>();
				space1.RunWorker(port);

				var remotePort = space2.ConnectWorker<Port<int>>(Environment.MachineName + ":8000");

				remotePort.Post(1);
				Assert.AreEqual(1, port.Receive(1000).Result);
			}
		}


		[Test]
		[ExpectedException(typeof(XcoCommunicationException))]
		public void AuthenticationFailed()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000;tcp.key=1234"),
				space2 = new XcoAppSpace("tcp.port=8001;tcp.key=xxxx"))
			{
				var port = new Port<int>();
				space1.RunWorker(port);

				var remotePort = space2.ConnectWorker<Port<int>>(Environment.MachineName + ":8000");
			}
		}
	}
}
